package com.software.task.service.impl;

import com.software.task.mapper.CategoryMapper;
import com.software.task.mapper.UserRoleMapper;
import com.software.task.pojo.Category;
import com.software.task.service.CategoryService;
import com.software.task.service.SubjectService;
import com.software.task.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;


import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
/**
 * @author lj20050120
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SubjectService subjectService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public void add(Category category) {
        //补充属性值
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        category.setUserId(userId);
        categoryMapper.add(category);
    }

    @Override
    public List<Category> list() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        return categoryMapper.list(userId);
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    @Override
    public void delete(Integer id) {
        if (subjectService.countByCategoryId(id) > 0) {
            throw new RuntimeException("该分类下存在课程，不能删除");
        }
        categoryMapper.delete(id);
    }

    @Override
    public void deleteById(Integer id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public boolean existsByCreateUserAndTaskId(Integer createUser, Integer taskId) {
        // 检查是否存在 create_user 和 task_id 相同的记录
        int count = categoryMapper.countByCreateUserAndTaskId(createUser, taskId);
        return count > 0;
    }

    @Override
    public boolean isStudent(Integer userId) {
        return userRoleMapper.existsByUserIdAndRoleId(userId, 3);
    }
}
